package org.onvivals.admin.module.pms.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.onvivals.common.param.PageParam;
import org.onvivals.common.web.PageResult;
import org.onvivals.common.web.Result;
import org.onvivals.module.pms.entity.PmsCode;
import org.onvivals.module.pms.param.PmsCodeParam;
import org.onvivals.module.pms.service.IPmsCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "激活码管理")
@RestController
@RequestMapping("/pms/code")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PmsCodeController {

	private final IPmsCodeService codeService;


	@Operation(summary = "分页查询全部激活码")
	@GetMapping("/page")
	public Result<PageResult<PmsCode>> page(PmsCodeParam param) {
		PageParam<PmsCode, PmsCodeParam> page = new PageParam<>(param);
		IPage<PmsCode> pa = codeService.page(page, page.getWrapper());
		PageResult<PmsCode> pageResult = new PageResult<>(pa.getRecords(), pa.getTotal());
		return Result.OK("查询成功", pageResult);
	}

	@Operation(summary = "查询全部激活码")
	@GetMapping()
	public Result<List<PmsCode>> list(PmsCodeParam param) {
		PageParam<PmsCode, PmsCodeParam> page = new PageParam<>(param);
		List<PmsCode> pmsLlmConfigList = codeService.list(page.getOrderWrapper());
		return Result.OK("查询成功", pmsLlmConfigList);
	}

	@Operation(summary = "根据id查询激活码")
	@GetMapping("/{id}")
	public Result<PmsCode> get(@PathVariable("id") Long id) {
		PmsCode pmsLlmConfig = codeService.getById(id);
		return Result.OK("查询成功", pmsLlmConfig);
	}

	@Operation(summary = "添加激活码")
	@PostMapping()
	public Result<?> save(@RequestBody PmsCode pmsLlmConfig) {
		pmsLlmConfig.setCode(IdUtil.getSnowflakeNextIdStr());
		if (codeService.save(pmsLlmConfig)) {
			return Result.OK("添加成功");
		}
		return Result.error("添加失败");
	}

	@Operation(summary = "修改激活码")
	@PutMapping()
	public Result<?> update(@RequestBody PmsCode pmsLlmConfig) {
		if (codeService.updateById(pmsLlmConfig)) {
			return Result.OK("修改成功");
		}
		return Result.error("修改失败");
	}

	@Operation(summary = "删除激活码")
	@DeleteMapping("/{id}")
	public Result<?> remove(@PathVariable("id") Long id) {
		if (codeService.removeById(id)) {
			return Result.OK("删除成功");
		}
		return Result.error("删除失败");
	}

	@GetMapping("/getAllQRCode")
	public Result<List<PmsCode>> getAllQRCode(Integer number) {
		//随机生成激活码
		for (int i = 0; i < number; i++) {
			PmsCode pmsCode = new PmsCode();
			pmsCode.setCode(IdUtil.getSnowflakeNextIdStr());
			pmsCode.setStatus(0);
			pmsCode.insert();
		}
		return Result.OK("生成成功");
	}

}
